package uz.edo.db.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * Created by IntelliJ IDEA.
 * User: said
 * Date: 1/13/12
 * Time: 11:35 PM
 * To change this template use File | Settings | File Templates.
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    private static Transaction tx;
    private static Session session;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Exception ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getSession(){
        if (session == null)
            session = getSessionFactory().openSession();
        return session;
    }

    public static void beginTransaction() throws Exception {
        tx = getSession().beginTransaction();
    }

    public static void commitTransaction() throws Exception {
        tx.commit();
    }

    public static void rollbackTransaction() throws Exception {
        tx.rollback();
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}
